<template>
  <div class="attract">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="图标">
        <template slot-scope="scope">
          <div @click="click(scope.row)">
            <el-upload
              class="avatar-uploader"
              :http-request="upLoad"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-preview="handlePictureCardPreview"
              accept="image/png,image/jpg,image/jpeg"
              action
            >
              <img
                v-if="scope.row.icon"
                :src="scope.row.icon"
                class="avatar_img"
                style="width: 50px; height: 50px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon img"></i>
            </el-upload>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="吸引概率（%）">
        <template slot-scope="scope">
          <el-input
            class="input"
            v-model="scope.row.successPoint"
            onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"
            placeholder="请输入"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="消耗电量">
        <template slot-scope="scope">
          <el-input
            class="input"
            v-model="scope.row.cost"
            onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"
            placeholder="请输入"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="info"
            plain
            size="small"
            @click="delBtn(scope.row, scope.$index)"
            >删除</el-button
          >
          <el-button
            type="primary"
            size="small"
            plain
            v-if="!scope.row.id"
            @click="addBtn(scope.row)"
            >确认</el-button
          >
          <el-button
            type="success"
            size="small"
            v-else
            plain
            @click="upBtn(scope.row)"
            >更新</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <br />
    <div class="btnadd">
      <el-button icon="el-icon-edit" class="btn1" @click="addRow"
        >添加
      </el-button>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
import {
  electricBackTime,
  electricBackTimeUpdata,
  electricAttractDel,
} from "@/api/operationManagement";
export default {
  components: { Pagination },
  data() {
    return {
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      type: "",
      keyName: "",
      targetObj: {},
    };
  },
  methods: {
    click(obj) {
      this.targetObj = obj;
    },
    async upLoad(file, obj) {
      console.log(obj);
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-" + res.data.regionId,
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      try {
        let fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
        this.targetObj.upIcon = fileNames;
        //fileNames上传文件的名称
        //file.file上传文件的内容
        let cli = client(this.dataObj);
        console.log(fileNames);
        console.log(file);
        let result = cli.multipartUpload(fileNames, file.file);
        self.$message({
          message: "上传成功",
          type: "success",
        });
      } catch (e) {
        self.$message.error("上传失败");
      }
    },
    handleAvatarSuccess(res, file) {
      //   console.log(URL.createObjectURL(file.raw));
      this.targetObj.icon = URL.createObjectURL(file.raw);
    },
    handlePictureCardPreview(file, obj) {
      console.log(obj);
      this.dialogImageUrl = file.url;
      this.dialogImageUrlB = file.url;
    },
    addRow() {
      this.tableData.push({
        successPoint: "",
        cost: "",
        upIcon: "",
        icon: "",
      });
    },
    delBtn(boj, index) {
      if (boj.id) {
        this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const res = await electricAttractDel({
              id: boj.id,
              keyName: this.keyName,
            });
            if (res.code == 0) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        this.tableData.splice(index, 1);
      }
    },
    getList() {
      electricBackTime().then((res) => {
        console.log(res);
        this.keyName = res.data.attractElectricValue.key_name;
        this.tableData = res.data.attractElectricValue.value;
      });
      // electricAttractList({
      //   page: this.page,
      //   pageSize: this.pageSize,
      // }).then((res) => {
      //   if (res.code == 0) {
      //     this.tableData = res.data.getList;
      //     this.total = res.data.total;
      //   }
      // });
    },
    upAndAdd(obj) {
      electricBackTimeUpdata(obj).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: "提交成功！",
            type: "success",
          });
          this.getList();
        }
      });
    },
    addBtn(obj) {
      if (obj.successPoint == "" || obj.cost == "") {
        this.$message({
          type: "error",
          message: "吸引概率或消耗电量不能为空！",
        });
        return;
      }
      this.upAndAdd({
        id: 0,
        keyName: this.keyName,
        value1: obj.successPoint,
        value2: obj.cost,
        upIcon: obj.upIcon,
      });
    },
    upBtn(obj) {
      if (obj.successPoint == "" || obj.cost == "") {
        this.$message({
          type: "error",
          message: "吸引概率或消耗电量不能为空！",
        });
        return;
      }
      this.upAndAdd({
        id: obj.id,
        keyName: this.keyName,
        value1: obj.successPoint,
        value2: obj.cost,
        upIcon: obj.upIcon,
      });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style scoped lang="less">
.attract {
  padding: 100px;
  .input {
    padding: 0 30px;
  }
  /deep/.el-table td,
  /deep/.el-table th.is-leaf {
    border: none !important;
  }
  .btnadd {
    // text-align: center;
    .btn1 {
      margin-left: 40px;
    }
  }
  .avatar_img {
    border: 1px dashed #ccc;
  }
}
</style>